import 'package:flutter/material.dart';
import 'package:flutter_billi/http/core/hi_error.dart';
import 'package:flutter_billi/http/dao/login_dao.dart';
import 'package:flutter_billi/navgator/hi_navigator.dart';
import 'package:flutter_billi/util/string_util.dart';
import 'package:flutter_billi/util/toast.dart';
import 'package:flutter_billi/widget/LoginButton.dart';
import 'package:flutter_billi/widget/appBar.dart';
import 'package:flutter_billi/widget/login_effect.dart';
import 'package:flutter_billi/widget/login_input.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool protect = false;
  bool loginEnable = false;

  String userName;
  String password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar("密码登陆", "注册", () {
        HiNavigator.getInstance().onJumpTo(RouteStatus.registration);
      }),
      body: ListView(
        children: [
          LoginEffect(
            protect: protect,
          ),
          LoginInput(
            "用户名",
            "请输入用户名",
            onChanged: (value) {
              userName = value;
              checkInput();
            },
          ),
          LoginInput(
            "密码",
            "请输入登陆密码",
            obscureText: true,
            focusChanged: (focus) {
              this.setState(() {
                protect = focus;
              });
            },
            onChanged: (value) {
              password = value;
              checkInput();
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 20, left: 20, right: 20),
            child: LoginButton(
              title: "登陆",
              enable: loginEnable,
              onPressed: send,
            ),
          )
        ],
      ),
    );
  }

  void checkInput() {
    if (isNotEmpty(userName) && isNotEmpty(password)) {
      this.setState(() {
        loginEnable = true;
      });
    }
  }

  void send() async {
    try {
      var result = await LoginDao.login(userName, password);
      print(result);
      if (result['code'] == 0) {
        // print("登陆成功");
        showToast("登陆成功");
        HiNavigator.getInstance().onJumpTo(RouteStatus.home);
      } else {
        print(result['msg']);
        showToast(result['msg']);
      }
    } on NeedAuth catch (err) {
      print(err);
      showToast(err.message);
    } on HiNetError catch (err) {
      print(err);
      showToast(err.message);
    }
  }
}
